﻿
namespace EasyNet.Solr.Impl
{
    using System.Collections.Generic;
    using System.Linq;
    using System.Xml.Linq;

    public class XmlFacetQueriesParser : ISolrResponseParser<string, IList<FacetField>>
    {
        public IList<FacetField> Parse(string result)
        {
            if (string.IsNullOrEmpty(result))
            {
                return null;
            }

            var xmlDoc = XDocument.Parse(result);

            var facetCounts = from e in xmlDoc.Root.Elements("lst")
                              where (string)e.Attribute("name") == "facet_counts"
                              select e;

            if (facetCounts == null)
            {
                return null;
            }

            var facetQueries = from e in facetCounts.Elements("lst")
                              where (string)e.Attribute("name") == "facet_queries"
                              select e;

            if (facetQueries == null)
            {
                return null;
            }

            var facetQueriesResult = new List<FacetField>(facetQueries.Single().Elements().Count());

            foreach (var element in facetQueries.Single().Elements())
            {
                facetQueriesResult.Add(new FacetField() { Name = element.Attribute("name").Value, Count = int.Parse(element.Value) });
            }

            return facetQueriesResult;
        }
    }
}
